// Centralized Axios instance & auth helpers to avoid hardcoded localhost
import axios from 'axios'
import { getToken, removeToken } from '@/utils/auth'

const api = axios.create({
  baseURL: '/api',
  // 增加超时时间：图像生成在后端可能接近或超过30秒，改为60秒以避免前端过早中断
  timeout: 60000
})

api.interceptors.request.use((config) => {
  const token = getToken()
  if (token) {
    config.headers = config.headers || {}
    config.headers.Authorization = `Bearer ${token}`
  }
  return config
})

api.interceptors.response.use(
  (res) => res,
  (error) => {
    if (error?.response?.status === 401) {
      // 触发一个自定义事件，方便全局监听弹出登录框
      removeToken()
      window.dispatchEvent(new CustomEvent('auth-expired'))
    }
    return Promise.reject(error)
  }
)

export default api

// Auth specific calls (optional convenience)
export const authApi = {
  login: (data) => api.post('/api/auth/login', data),
  register: (data) => api.post('/api/auth/register', data),
  guest: () => api.post('/api/auth/guest'),
  me: () => api.get('/api/auth/me')
}